package procinfo

import (
	"bytes"
	"sort"
	"strconv"
	"time"
	log "ac-common-go/glog"
	"ac-julink/tool/config"
	"ac-julink/tool/data"
)

var keyIndexMap map[int]int

var reqInfoSlice []int

func Init() {
	keyIndexMap = make(map[int]int)
	keyIndexMap[data.DEVICE_AUTHENTICATION] = 0
	keyIndexMap[data.EXCHANGE_ENCRYPTION_KEY] = 1
	keyIndexMap[data.RETRIVE_SYSTEM_CONFIG] = 2
	keyIndexMap[data.SEND_CONTROL_COMMAND] = 3
	keyIndexMap[data.SEND_QUERY_COMMAND] = 4
	keyIndexMap[data.QUERY_VERSON_COMMAND] = 5
	keyIndexMap[data.SEND_OTA_COMMAND] = 6
	keyIndexMap[data.QUERY_OTA_COMMAND] = 7
	keyIndexMap[data.BIND_DEV_COMMAND] = 8
	keyIndexMap[data.UNBIND_DEV_COMMAND] = 9
	keyIndexMap[data.GET_BIND_DEV_COMMAND] = 10
	keyIndexMap[data.GET_HOME_DEVLIST_COMMAND] = 11
	keyIndexMap[data.SEND_DEVINFO_CHANGE_COMMAND] = 12
	keyIndexMap[data.DEVICE_EXTINFO_STORE] = 13
	keyIndexMap[data.DEVICE_RESET] = 14
	keyIndexMap[data.GET_SCENE_LIST_COMMAND] = 15
	keyIndexMap[data.GET_SCENE_INFO_COMMAND] = 16
	keyIndexMap[data.SEND_SCENE_MODIFY_COMMAND] = 17
	keyIndexMap[data.SEND_SCENE_EXE_COMMAND] = 18
	keyIndexMap[data.REPORT_STATUS_COMMAND] = 19
	keyIndexMap[data.REPORT_HEARTBEAT_COMMAND] = 20
	keyIndexMap[data.SEND_MCU_UPGRADE_COMMAND] = 21//xwj add 2018/12/6
	keyIndexMap[data.REPORT_STATUS_UPDATE] = 22
	keyIndexMap[data.SEND_CONFIG_DATA_COMMAND] = 23
	keyIndexMap[data.REPORT_CONFIG_DATA] = 24
	reqInfoSlice = make([]int, len(keyIndexMap))
	go PrintReqInfo()
}

func AddCount(key int) {
	index := keyIndexMap[key]
	reqInfoSlice[index] = reqInfoSlice[index] + 1
}

func PrintReqInfo() {
	sleepSec, ok := config.GetConfigIntValue("WGNS", "status_print_sleep")
	if !ok {
		sleepSec = 60
	}
	sorted_keys := make([]int, 0)
	for key, _ := range keyIndexMap {
		sorted_keys = append(sorted_keys, key)
	}
	sort.Ints(sorted_keys)
	var processInfo bytes.Buffer
	var reqIndex int
	for {
		for _, key := range sorted_keys {
			reqIndex = keyIndexMap[key]
			processInfo.WriteString("[")
			processInfo.WriteString(strconv.Itoa(key))
			processInfo.WriteString("]:")
			processInfo.WriteString(strconv.Itoa(reqInfoSlice[reqIndex]))
			processInfo.WriteString("/")
			processInfo.WriteString(strconv.Itoa(sleepSec))
			processInfo.WriteString("s,")
			reqInfoSlice[reqIndex] = 0
		}
		log.Warningf("REQ STATUS===>%s", processInfo.String())
		processInfo.Reset()

		time.Sleep(time.Second * time.Duration(sleepSec))
	}
}
